package demoflink.state;

import demoflink.entity.WaterSensor;
import demoflink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 检测每种检测器 如果差值超过10进行报警
 */
public class KeyedMapStateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
                .setBootstrapServers("node1:9092,node2:9092,node3:9092")
                .setGroupId("local")
                .setTopics("first")
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .setStartingOffsets(OffsetsInitializer.latest())
                .build();
        env.setParallelism(1);

        // 指定水位线
        WatermarkStrategy<WaterSensor> strategy = WatermarkStrategy
                //乱序
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((element,ts)-> element.getTs()*1000L);
        env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource")
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(strategy)
                .keyBy(x -> x.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    MapState<Integer,Integer> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);

                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<Integer, Integer>("mapState",Types.INT,Types.INT));
                    }

                    @Override
                    public void processElement(WaterSensor waterSensor, KeyedProcessFunction<String, WaterSensor, String>.Context context, Collector<String> collector) throws Exception {
                        collector.collect(String.valueOf(waterSensor.getVc()));
                    }
                })
                .print();
        env.execute();
    }
}
